package client

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"sync"
	"wxp2p/common"

	"github.com/pion/webrtc/v3"
)

// client-client
func RunWebrtcOffer(clientId string) {
	var candidatesMux sync.Mutex
	pendingCandidates := make([]*webrtc.ICECandidate, 0)

	// Create a new RTCPeerConnection
	peerConnection, err := webrtc.NewPeerConnection(common.WebrtcConfig)
	if err != nil {
		panic(err)
	}
	defer func() {
		if cErr := peerConnection.Close(); cErr != nil {
			fmt.Printf("cannot close peerConnection: %v\n", cErr)
		}
	}()

	// When an ICE candidate is available send to the other Pion instance
	// the other Pion instance will add this candidate by calling AddICECandidate
	peerConnection.OnICECandidate(func(c *webrtc.ICECandidate) {
		if c == nil {
			return
		}

		candidatesMux.Lock()
		defer candidatesMux.Unlock()
		desc := peerConnection.RemoteDescription()
		if desc == nil {
			pendingCandidates = append(pendingCandidates, c)
		} else {
			sig := common.P2PSignal{ClientId: clientId, SigType: common.ECandidate, Content: c.ToJSON().Candidate}
			P2PSignalSendChan <- sig
		}
	})

	// allows the other Pion instance to send us ICE candidates
	// This allows us to add ICE candidates faster, we don't have to wait for STUN or TURN
	// candidates which may be slower
	go func() {
		for sig := range P2PSignalRecvChan {
			switch sig.SigType {
			case common.ECandidate:
				if candidateErr := peerConnection.AddICECandidate(webrtc.ICECandidateInit{Candidate: string(sig.Content)}); candidateErr != nil {
					panic(candidateErr)
				}
			case common.ESdp:
				sdp := webrtc.SessionDescription{}
				json.Unmarshal([]byte(sig.Content), &sdp)
				if sdpErr := peerConnection.SetRemoteDescription(sdp); sdpErr != nil {
					panic(sdpErr)
				}
				candidatesMux.Lock()
				for _, c := range pendingCandidates {
					p2psig := common.P2PSignal{ClientId: clientId, SigType: common.ECandidate, Content: c.ToJSON().Candidate}
					P2PSignalSendChan <- p2psig
				}
				candidatesMux.Unlock()
			}
		}
	}()

	// Create a datachannel with label 'data'
	dataChannel, err := peerConnection.CreateDataChannel("data", nil)
	if err != nil {
		panic(err)
	}

	// Set the handler for Peer connection state
	// This will notify you when the peer has connected/disconnected
	peerConnection.OnConnectionStateChange(func(s webrtc.PeerConnectionState) {
		log.Printf("p2p连接状态改变: %s\n", s.String())
		if s == webrtc.PeerConnectionStateConnected {
			log.Println("p2p连接成功")
		}
		if s == webrtc.PeerConnectionStateFailed || s == webrtc.PeerConnectionStateDisconnected {
			// Wait until PeerConnection has had no network activity for 30 seconds or another failure. It may be reconnected using an ICE Restart.
			// Use webrtc.PeerConnectionStateDisconnected if you are interested in detecting faster timeout.
			// Note that the PeerConnection may come back from PeerConnectionStateDisconnected.
			log.Println("p2p连接失败正在退出")
			os.Exit(0)
		}
	})

	// Register channel opening handling
	dataChannel.OnOpen(func() {
		log.Println("p2p数据通道准备就绪")
		for buf := range LocalPortSendChan {
			sendErr := dataChannel.Send(buf)
			if sendErr != nil {
				panic(sendErr)
			}
		}
	})

	// Register text message handling
	dataChannel.OnMessage(func(msg webrtc.DataChannelMessage) {
		LocalPortRecvChan <- msg.Data
	})

	// Create an offer to send to the other process
	offer, err := peerConnection.CreateOffer(nil)
	if err != nil {
		panic(err)
	}

	// Sets the LocalDescription, and starts our UDP listeners
	// Note: this will start the gathering of ICE candidates
	if err = peerConnection.SetLocalDescription(offer); err != nil {
		panic(err)
	}

	// Send our offer to the HTTP server listening in the other process
	payload, err := json.Marshal(offer)
	if err != nil {
		panic(err)
	}
	p2psig := common.P2PSignal{ClientId: clientId, SigType: common.ESdp, Content: string(payload)}
	P2PSignalSendChan <- p2psig
	// Block forever
	select {}
}

func BeginLinkClient(clientId string) {
	p2psig := common.P2PSignal{ClientId: clientId, SigType: common.ELinkClient, Content: ""}
	P2PSignalSendChan <- p2psig
}
